<!-- 经销商列表 -->
<template>
  <div class="goodsApplyRule sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="规则名称:">
              <el-input v-model="query.ruleName" placeholder="请输入规则名称" clearable/>
            </el-form-item>
            <el-form-item label="状态:">
              <el-select v-model="query.enableStatus" placeholder="请选择" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="商品申请规则数据" icon="Histogram" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中">
        <el-table ref="tableRef" :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="规则名称" prop="ruleName" align="center"></el-table-column>
          <el-table-column label="有效区域" header-align="center">
            <template #default="{row}">
              <span>{{ row.provinceName + row.cityName + row.regionName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="绑定条件" header-align="center">
            <template #default="{row}">
              <p v-for="(item, index) in row.bindRuleDetailList" :key="index">
                {{ $getDictValueByKey(item.ruleType, ruleTypes) + '：' + item.conditions }}
              </p>
            </template>
          </el-table-column>
          <el-table-column label="绑定数量" prop="sellNum" align="center"></el-table-column>
          <el-table-column label="启用状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已启用' : '已禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="240">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.ruleId)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button 
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'" 
                link 
                @click="doUpdateStatus(row)">
                {{row.enableStatus ? '禁用' : '启用'}}
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.ruleId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.ruleId ? '编辑' : '新增'" top="10vh" width="46%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="large" label-position="right" label-width="100px">
        <el-form-item label="规则名称:" prop="ruleName" required>
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" clearable/>
        </el-form-item>
        <el-form-item label="注册区域:" prop="region">
          <region-select v-model="form.region" size="large" ref="regionRef"></region-select>
        </el-form-item>
        <el-form-item label="绑定商品数:" prop="sellNum">
          <el-input v-model="form.sellNum" type="number" placeholder="请输入绑定商品数" clearable/>
        </el-form-item>
        <el-form-item v-if="!form.ruleId" label="是否启用:" prop="enableStatus">
          <el-switch 
            v-model="form.enableStatus"
            :active-value="1"
            :inactive-value="0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"/>
        </el-form-item>
        <el-form-item label="条件:" prop="productBindRuleDetailsFormList" required>
          <el-button type="primary" @click="doCondition(true)">新增条件</el-button>
          <el-table ref="tableRef" :data="form.productBindRuleDetailsFormList" border style="margin-top: 10px;">
            <el-table-column label="序号" type="index" align="center" width="70"/>
            <el-table-column label="条件类型" prop="ruleType" align="center">
              <template #default="{row}">
                <el-select v-model="row.ruleType" placeholder="请选择">
                  <el-option v-for="item in ruleTypes" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="条件" prop="conditions" align="center">
              <template #default="{row}">
                <el-input v-model="row.conditions" placeholder="请输入条件" clearable/>
              </template>
            </el-table-column>
            <el-table-column label="说明" prop="description" align="center">
              <template #default="{row}">
                <el-input v-model="row.description" placeholder="请输入说明" clearable/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template #default="{$index}">
                <el-button type="danger" icon="Delete" link @click="doCondition(false, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="goodsApplyRule">
  import { cudGoodsApplyRuleApi, getGoodsApplyRuleListPagesApi, getGoodsApplyRuleInfoApi, updateGoodsApplyRuleStatusApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated, computed } from 'vue'
  import { useStore } from 'vuex' 

  const store = useStore()

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties

  const formRef = ref(null)
  const regionRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    query: {
      ruleName: '',
      enableStatus: '',
      current: 1,
      size: 20,
      total: 0
    },
    form: {
      ruleId: '',
      ruleName: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      sellNum: '',
      enableStatus: 1,
      productBindRuleDetailsFormList: [],
      region: []
    },
    rules: {
      ruleName: [{ required: true, message: '请输入规则名称', trigger: ['blur', 'change'] }],
      sellNum: [{ required: true, message: '请输入绑定商品数', trigger: ['blur', 'change'] }],
      productBindRuleDetailsFormList: [{ required: true, message: '请添加调条件', trigger: ['blur', 'change'] }]
    },
    dataList: []
  })
  let {loading, show, query, form, rules, dataList} = toRefs(currentData)

  // 获取缓存页面数据
  let ruleTypes = computed(() => {
    return store.getters.getDictByKey('PRODUCT_RULE_TYPE')
  })

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getGoodsApplyRuleListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.ruleId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.ruleId ? '修改' : '新增'}`)
          currentData.form.provinceCode = currentData.form.region[0] || ''
          currentData.form.cityCode = currentData.form.region[1] || ''
          currentData.form.regionCode = currentData.form.region[2] || ''
          cudGoodsApplyRuleApi(`${currentData.form.ruleId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.form.ruleId ? currentData.query.current : 1)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改前弹窗
  function toUpdate(ruleId) {
    getGoodsApplyRuleInfoApi(ruleId).then(res => {
      if(res.code === '200') {
        const datas = res.data
        let regionData = []
        if(datas.provinceCode) regionData.push(datas.provinceCode)
        if(datas.cityCode) regionData.push(datas.cityCode)
        if(datas.regionCode) regionData.push(datas.regionCode)
        currentData.form = datas
        currentData.form.region = regionData
        currentData.form.productBindRuleDetailsFormList = datas.productBindRuleDetailList
        delete currentData.form.productBindRuleDetailList
        currentData.show  = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 启用或禁用
  function doUpdateStatus(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '禁用' : '启用'}吗？`).then(() => {
      let loading = currentThis.$loading('正在处理，请耐心等待')
      updateGoodsApplyRuleStatusApi({
        ruleId: e.ruleId,
        enableStatus: e.enableStatus ? 0 : 1
      }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 删除
  function doDelete(ruleId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      cudGoodsApplyRuleApi('delete', { id: ruleId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 添加或删除绑定条件
  function doCondition(type, index) {
    if(type) {
      currentData.form.productBindRuleDetailsFormList.push({ ruleType: '', condition: '', description: '' })
    } else {
      currentData.form.productBindRuleDetailsFormList.splice(index, 1)
    }
  }
  
  // 重置查询
  function resetSearch() {
    currentData.query.ruleName = ''
    currentData.query.enableStatus = ''
    load(1)
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      ruleId: '',
      ruleName: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      sellNum: '',
      enableStatus: 1,
      productBindRuleDetailsFormList: [],
      region: []
    }
    formRef.value.resetFields()
    regionRef.value.resetData()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.goodsApplyRule{
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
      .el-form-item__content{
        >.el-input{
          width: 300px;
        }
        >.el-select{
          .el-input{
            width: 300px;
          }
        }
      }
    }
  }
}
</style>